//
//  HSQKeyBoardTextView.m
//  LiTianDecoration
//
//  Created by administrator on 2018/7/24.
//  Copyright © 2018年 administrator. All rights reserved.
//

#import "HSQKeyBoardTextView.h"
#import "HWEmotion.h"
#import "HWEmotionAttachment.h"
#import "UITextView+Extension.h"

static float textFont = 25; //文案字体大小

@interface HSQKeyBoardTextView ()

/**
 文字最大高度
 */
@property (nonatomic, assign) CGFloat maxTextH;

@end

@implementation HSQKeyBoardTextView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        if (!self.textFont) {
            
            self.textFont = [UIFont systemFontOfSize:textFont];
        }
        [self setup];
    }
    return self;
}

- (void)setup {
    
    self.scrollEnabled = NO;
    
    self.scrollsToTop = NO;
    
    self.showsHorizontalScrollIndicator = NO;
    
    self.enablesReturnKeyAutomatically = YES;
    
    //实时监听textView值得改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:self];
}

#pragma mark ====== 计算高度 ======
//UITextViewDelegate代理, 在这里让textView高度自适应, 同时设置最大高度, 类似于QQ微信输入框的效果
- (void)textDidChange {
    
    //计算高度
    CGFloat height = ceilf([self sizeThatFits:CGSizeMake(self.frame.size.width, MAXFLOAT)].height);
    
    if (height > _maxTextH) {
        
        height = _maxTextH;
        
        self.scrollEnabled = YES;   //当textView大于最大高度的时候让其可以滚动
    }
    else
    {
        self.scrollEnabled = NO;
        
        if (_textChangedBlock && self.scrollEnabled == NO) {
            
            _textChangedBlock(height);
        }
    }
    [self layoutIfNeeded];
}

#pragma mark ====== 设置placeholder ======
- (void)setMaxNumberOfLines:(NSUInteger)maxNumberOfLines {
    
    _maxNumberOfLines = maxNumberOfLines;
    /**
     *  根据最大的行数计算textView的最大高度
     *  计算最大高度 = (每行高度 * 总行数 + 文字上下间距)
     */
    _maxTextH = ceil(self.font.lineHeight * maxNumberOfLines + self.textContainerInset.top + self.textContainerInset.bottom);
}

#pragma mark ====== 回调 ======
- (void)textValueDidChanged:(TextHeightChangedBlock)block {
    
    _textChangedBlock = block;
}


- (void)insertEmotion:(HWEmotion *)emotion{
    
    if (emotion.code) {
        
        // insertText : 将文字插入到光标所在的位置
        [self insertText:emotion.code.emoji];
        
    } else if (emotion.png) {
        // 加载图片
        HWEmotionAttachment *attch = [[HWEmotionAttachment alloc] init];
        
        // 传递模型
        attch.emotion = emotion;
        
        // 设置图片的尺寸
        CGFloat attchWH = self.font.lineHeight;
        attch.bounds = CGRectMake(0, -4, attchWH, attchWH);
        
        // 根据附件创建一个属性文字
        NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:attch];
        
        // 插入属性文字到光标位置
        [self insertAttributedText:imageStr settingBlock:^(NSMutableAttributedString *attributedText) {
            
            // 设置字体
            [attributedText addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, attributedText.length)];
        }];
    }
}

- (NSString *)fullText{
    
    NSMutableString *fullText = [NSMutableString string];
    
    // 遍历所有的属性文字（图片、emoji、普通文字）
    [self.attributedText enumerateAttributesInRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
        // 如果是图片表情
        HWEmotionAttachment *attch = attrs[@"NSAttachment"];
        if (attch) { // 图片
            [fullText appendString:attch.emotion.chs];
        } else { // emoji、普通文本
            // 获得这个范围内的文字
            NSAttributedString *str = [self.attributedText attributedSubstringFromRange:range];
            [fullText appendString:str.string];
        }
    }];
    
    
    return fullText;
}


#pragma mark ====== 移除监听 ======
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
